import { defineStore } from "pinia";
import common_util from "@/util/common_util.js";
import { ElMessage, ElMessageBox } from "element-plus";

export const useForumStore = defineStore("forum", {
  state: () => ({
    /**
     * @description 帖子列表，用于在社区首页展示
     * @type {Array<object>}
     */
    posts: [],
    /**
     * @description 当前正在查看的单个帖子的详细信息，包括帖子本身和其下的回复
     * @type {object | null}
     */
    currentThread: null,
    /**
     * @description 当前用户发布的帖子列表
     * @type {Array<object>}
     */
    currentUserPosts: [],
    /**
     * @description 当前用户发布的回复列表
     * @type {Array<object>}
     */
    currentUserReplies: [],
    /**
     * @description 用于分页的总帖子数
     */
    totalPosts: 0,
    totalCurrentUserPosts: 0,
    totalCurrentUserReplies: 0,

    sections: [],
    totalSections: 0,

    /**
 * @description 当前正在查看的单个社区板块的信息
 * @type {object | null}
 */
    currentSection: null,

    /**
     * @description 当前用户的消息列表
     * @type {Array<object>}
     */
    messages: [],

    /**
     * @description 用于消息分页的总条目数
     */
    totalMessages: 0,

    /**
 * @description 跨页面导航的目标，用于从消息中心跳转到指定帖子和回复
 * @type {{postId: number, replyId: number|null}|null}
 */
    navigationTarget: null,


    /**
     * @description 加载状态，用于在API请求期间显示加载动画
     */
    loading: false,
  }),

  actions: {
    // =================================================================
    // WebSocket & 主题订阅管理
    // =================================================================

    /**
     * @description 订阅一个主题（主页或特定帖子）
     * @param {string} topic - 要订阅的主题 ('main' 或 postId)
     * @param {function} [onSuccess] - 成功回调
     */
    subscribeToTopic(topic, onSuccess) {
      common_util.put(
        `/api/forum/topics/${topic}`,
        {},
        {},
        (data) => {
          ElMessage.success(`成功订阅主题: ${topic}`);
          if (onSuccess) onSuccess(data);
        },
        (message) => ElMessage.error(`订阅失败: ${message}`),
      );
    },

    /**
     * @description 取消订阅一个主题
     * @param {string} topic - 要取消订阅的主题 ('main' 或 postId)
     * @param {function} [onSuccess] - 成功回调
     */
    unsubscribeFromTopic(topic, onSuccess) {
      common_util.delete(
        `/api/forum/topics/${topic}`,
        {},
        (data) => {
          ElMessage.info(`已取消订阅主题: ${topic}`);
          if (onSuccess) onSuccess(data);
        },
        (message) => ElMessage.error(`取消订阅失败: ${message}`),
      );
    },

    // =================================================================
    // 帖子管理 (Post Management)
    // =================================================================

    /**
     * @description 获取所有帖子（支持分页）
     * @param {object} params - 包含 pageNo 和 pageSize 的对象
     */
    fetchPosts(params = { pageNo: 1, pageSize: 10 }) {
      this.loading = true;
      common_util.get(
        "/api/forum/posts",
        params,
        (data, total) => {
          this.posts = data;
          this.totalPosts = total;
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取帖子列表失败: ${message}`);
          this.loading = false;
        },
      );
    },

    /**
     * @description 获取指定帖子的详细信息及其所有回复
     * @param {number} postId - 帖子ID
     */
    fetchPostThread(postId, onSuccess, onFailure) {
      this.loading = true;
      common_util.get(
        `/api/forum/posts/${postId}`,
        {},
        (data) => {
          this.currentThread = data;
          this.loading = false;
          // 在成功获取并设置数据后，执行传入的 onSuccess 回调
          if (onSuccess) {
            onSuccess(data);
          }
        },
        (message) => {
          ElMessage.error(`获取帖子详情失败: ${message}`);
          this.loading = false;
          // 执行传入的 onFailure 回调
          if (onFailure) {
            onFailure(message);
          }
        },
      );
    },

    /**
     * @description 创建一个新帖子
     * @param {object} postData - 包含 title 和 content 的对象
     * @param {function} [onSuccess] - 成功回调
     */
    createPost(postData, onSuccess, onFailure) {
      this.loading = true;
      common_util.post(
        "/api/forum/posts",
        postData,
        {},
        (data) => {
          ElMessage.success("帖子发布成功！");
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message,code) => {
          if (onFailure) {
            onFailure(message, code); 
          } else {
            // 如果没有提供 onFailure 回调，则使用默认的 ElMessage 提示
            ElMessage.error(`发布失败: ${message}`);
          }
          this.loading = false;
        },
      );
    },

    /**
     * @description 更新一个帖子
     * @param {number} postId - 帖子ID
     * @param {object} postData - 包含 title 和 content 的对象
     * @param {function} [onSuccess] - 成功回调
     */
    updatePost(postId, postData, onSuccess) {
      this.loading = true;
      common_util.put(
        `/api/forum/posts/${postId}`,
        postData,
        {},
        (data) => {
          ElMessage.success("帖子更新成功！");
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`更新失败: ${message}`);
          this.loading = false;
        },
      );
    },

    /**
     * @description 删除一个帖子
     * @param {number} postId - 帖子ID
     * @param {function} [onSuccess] - 成功回调
     */
    deletePost(postId, onSuccess) {
      ElMessageBox.confirm("确定要删除这个帖子吗？此操作不可恢复。", "警告", {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          common_util.delete(
            `/api/forum/posts/${postId}`,
            {},
            (data) => {
              ElMessage.success("帖子删除成功！");
              if (onSuccess) onSuccess(data);
              this.loading = false;
            },
            (message) => {
              ElMessage.error(`删除失败: ${message}`);
              this.loading = false;
            },
          );
        })
        .catch(() => ElMessage.info("已取消删除"));
    },

    // =================================================================
    // 回复管理 (Reply Management)
    // =================================================================

    /**
     * @description 创建一个回复（可用于回复帖子或回复其他回复）
     * @param {number} postId - 所属帖子的ID
     * @param {object} replyData - 包含 content 和可选的 FatherReplyId
     * @param {function} [onSuccess] - 成功回调
     */
    createReply(postId, replyData, onSuccess) {
      this.loading = true;
      common_util.post(
        `/api/forum/posts/${postId}/replies`,
        replyData,
        {},
        (data) => {
          ElMessage.success("回复成功！");
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`回复失败: ${message}`);
          this.loading = false;
        },
      );
    },

    /**
     * @description 删除一个回复及其所有子回复
     * @param {number} replyId - 要删除的回复ID
     * @param {function} [onSuccess] - 成功回调
     */
    deleteReply(replyId, onSuccess) {
      this.loading = true;
      common_util.delete( // 注意：文档中写的是 POST，但语义上应为 DELETE，这里使用 DELETE
        `/api/forum/replies/${replyId}`,
        {},
        (data) => {
          ElMessage.success("回复删除成功！");
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`删除回复失败: ${message}`);
          this.loading = false;
        },
      );
    },

    /**
     * @description 获取某个特定回复下的所有子回复
     * @param {number} replyId - 父回复的ID
     */
    fetchRepliesOfReply(replyId) {
      this.loading = true;
      common_util.get(
        `/api/forum/replies/${replyId}`,
        {},
        (data) => {
          // 这里可以根据需要将获取到的子回复更新到 specificReplyThread 或其他 state 中
          console.log(`获取到回复 ${replyId} 的子回复:`, data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取子回复列表失败: ${message}`);
          this.loading = false;
        }
      );
    },

    // =================================================================
    // 获取当前用户的帖子和回复
    // =================================================================

    /**
     * @description 获取当前登录用户的所有帖子
     * @param {object} params - 分页参数 { pageNo, pageSize }
     */
    fetchCurrentUserPosts(params = { pageNo: 1, pageSize: 10 }) {
      this.loading = true;
      common_util.get(
        "/api/forum/currentUserPosts",
        params,
        (data, total) => { // <-- 接收 data 和 total
          this.currentUserPosts = data;
          this.totalCurrentUserPosts = total; // <-- 新增：保存总数
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取我的帖子失败: ${message}`);
          this.loading = false;
        },
      );
    },

    /**
     * @description 获取当前登录用户的所有回复
     * @param {object} params - 分页参数 { pageNo, pageSize }
     */
    fetchCurrentUserReplies(params = { pageNo: 1, pageSize: 10 }) {
      this.loading = true;
      common_util.get(
        "/api/forum/currentUserReplies",
        params,
        (data, total) => { // <-- 接收 data 和 total
          this.currentUserReplies = data;
          this.totalCurrentUserReplies = total; // <-- 新增：保存总数
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取我的回复失败: ${message}`);
          this.loading = false;
        },
      );
    },

    /**
     * @description 根据板块ID获取其下的帖子列表（支持分页）
     * @param {number} sectionId - 社区板块ID
     * @param {object} params - 分页参数 { pageNo, pageSize }
     */
    fetchPostsBySection(sectionId, params = { pageNo: 1, pageSize: 10 }) {
      this.loading = true;
      common_util.get(
        `/api/forum/sections/${sectionId}/posts`,
        params,
        (data, total) => {
          this.posts = data; // 更新帖子列表
          this.totalPosts = total;
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取板块帖子失败: ${message}`);
          this.loading = false;
        }
      );
    },

    /**
     * @description 根据多种联合条件筛选帖子（支持分页）
     * @param {object} params - 查询参数，可包含 { pageNo, pageSize, keyWord, sectionId }
     */
    searchPosts(params) {
      this.loading = true;
      common_util.get(
        "/api/forum/sections/posts",
        params,
        (data, total) => {
          this.posts = data;
          this.totalPosts = total;
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`搜索帖子失败: ${message}`);
          this.loading = false;
        }
      );
    },

    /**
     * @description (管理员) 删除帖子，可附带原因
     * @param {number} postId - 帖子ID
     * @param {string} [reason] - 删除原因 (可选，管理员操作时需要)
     * @param {function} [onSuccess] - 成功回调
     */
    deletePostAsAdmin(postId, reason, onSuccess) {
      ElMessageBox.confirm("确定要删除这个帖子吗？此操作不可恢复。", "管理员操作", {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          // 将 reason 作为 URL 查询参数
          const params = reason ? { reason: reason } : {};
          common_util.delete(
            `/api/forum/posts/${postId}`,
            params, // 此处传递参数
            (data) => {
              ElMessage.success("帖子已由管理员删除！");
              if (onSuccess) onSuccess(data);
              this.loading = false;
            },
            (message) => {
              ElMessage.error(`删除失败: ${message}`);
              this.loading = false;
            }
          );
        })
        .catch(() => ElMessage.info("已取消删除"));
    },

    /**
     * @description (管理员) 递归删除回复，可附带原因
     * @param {number} replyId - 回复ID
     * @param {string} [reason] - 删除原因 (可选，管理员操作时需要)
     * @param {function} [onSuccess] - 成功回调
     */
    deleteReplyAsAdmin(replyId, reason, onSuccess) {
      this.loading = true;
      const params = reason ? { reason: reason } : {};
      common_util.delete(
        `/api/forum/replies/${replyId}`,
        params,
        (data) => {
          ElMessage.success("回复已由管理员删除！");
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`删除回复失败: ${message}`);
          this.loading = false;
        }
      );
    },
    /**
     * @description 获取所有社区板块
     * @param {function} [onSuccess] - 成功回调
     */
    fetchSections(onSuccess) {
      this.loading = true;
      common_util.get(
        "/api/forum/sections",
        {},
        (data, total) => {
          this.sections = data;
          this.totalSections = total;
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取社区板块失败: ${message}`);
          this.loading = false;
        }
      );
    },
    /**
     * @description (管理员) 删除帖子，可附带原因
     * @param {number} postId - 帖子ID
     * @param {string} [reason] - 删除原因
     * @param {function} [onSuccess] - 成功回调
     */
    deletePostAsAdmin(postId, reason, onSuccess) {
      this.loading = true;
      // 将 reason 作为 URL 查询参数
      const params = reason ? { reason: reason } : {};
      common_util.delete(
        `/api/forum/posts/${postId}`,
        params,
        (data) => {
          ElMessage.success("帖子已由管理员删除！");
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`删除失败: ${message}`);
          this.loading = false;
        }
      );
    },

    /**
     * @description (管理员) 递归删除回复，可附带原因
     * @param {number} replyId - 回复ID
     * @param {string} [reason] - 删除原因
     * @param {function} [onSuccess] - 成功回调
     */
    deleteReplyAsAdmin(replyId, reason, onSuccess) {
      this.loading = true;
      const params = reason ? { reason: reason } : {};
      common_util.delete(
        `/api/forum/replies/${replyId}`,
        params,
        (data) => {
          ElMessage.success("回复已由管理员删除！");
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`删除回复失败: ${message}`);
          this.loading = false;
        }
      );
    },
    /**
 * @description 根据ID获取单个社区板块的信息
 * @param {number} sectionId - 板块ID
 * @param {function} [onSuccess] - 成功回调
 */
    fetchSectionById(sectionId, onSuccess) {
      this.loading = true;
      common_util.get(
        `/api/forum/sections/${sectionId}`,
        {},
        (data) => {
          this.currentSection = data;
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取板块信息失败: ${message}`);
          this.loading = false;
        }
      );
    },

    /**
     * @description 获取当前用户的消息列表（支持分页和已读/未读筛选）
     * @param {object} params - 查询参数，可包含 { isRead, pageNo, pageSize }
     * @param {function} [onSuccess] - 成功回调
     */
    fetchMessages(params, onSuccess) {
      this.loading = true;
      common_util.get(
        "/api/forum/messages",
        params,
        (data, total) => {
          this.messages = data;
          this.totalMessages = total;
          if (onSuccess) onSuccess(data, total);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取消息列表失败: ${message}`);
          this.loading = false;
        }
      );
    },

    /**
     * @description 根据ID获取单条消息详情
     * @param {number} messageId - 消息ID
     * @param {function} [onSuccess] - 成功回调
     */
    fetchMessageById(messageId, onSuccess) {
      this.loading = true;
      common_util.get(
        `/api/forum/messages/${messageId}`,
        {},
        (data) => {
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取消息详情失败: ${message}`);
          this.loading = false;
        }
      );
    },

    /**
     * @description 更新消息为已读状态
     * @param {number} messageId - 消息ID
     * @param {function} [onSuccess] - 成功回调
     */
    markMessageAsRead(messageId, onSuccess) {
      this.loading = true;
      // 调用 common_util.put 并传入正确的参数
      // 第三个参数 params 为空对象 {}
      common_util.put(
        `/api/forum/messages/${messageId}/status`, // url
        {}, // data (请求体为空)
        {}, // params (URL查询参数为空)
        (data) => { // success 回调
          ElMessage.success("消息已标记为已读");
          const message = this.messages.find(m => m.message.id === messageId);
          if (message) {
            message.message.isRead = 1;
          }
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => { // failure 回调
          ElMessage.error(`更新消息状态失败: ${message}`);
          this.loading = false;
        }
      );
    },

    /**
     * @description 逻辑删除一条消息
     * @param {number} messageId - 消息ID
     * @param {function} [onSuccess] - 成功回调
     */
    deleteMessage(messageId, onSuccess) {
      // 新增：添加一个确认弹窗
      ElMessageBox.confirm(
        '您确定要删除这条消息吗？此操作不可撤销。',
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        // 用户确认后，再执行原来的删除逻辑
        this.loading = true;
        common_util.delete(
          `/api/forum/messages/${messageId}`,
          {},
          (data) => {
            ElMessage.success("消息删除成功");
            this.messages = this.messages.filter(m => m.message.id !== messageId);
            this.totalMessages--;
            if (onSuccess) onSuccess(data);
            this.loading = false;
          },
          (message) => {
            ElMessage.error(`删除消息失败: ${message}`);
            this.loading = false;
          }
        );
      }).catch(() => {
        // 用户点击了“取消”
        ElMessage.info('已取消删除');
      });
    },
    // =================================================================
    // 导航辅助 (Navigation Helpers)
    // =================================================================

    /**
     * @description 设置一个临时的导航目标
     * @param {{postId: number, replyId: number|null}} target - 导航目标
     */
    setNavigationTarget(target) {
      this.navigationTarget = target;
    },

    /**
     * @description 清除临时的导航目标
     */
    clearNavigationTarget() {
      this.navigationTarget = null;
    },
  },
});